# coding=utf8
__author__ = 'lijian'
import datetime


def strToBcd(str):
    # bcd =[]
    len1 = len(str)

    if len1 % 2:
        addup = 1
        bcd = [0] * (len1 / 2 + 1)
    else:
        addup = 0
        bcd = [0] * (len1 / 2)
    j = 0
    for i in range(0, len1):
        uc = int(str[i])
        # print uc + 1, addup
        if addup:
            bcd[j] |= uc & 0x0f
            j += 1
        else:
            bcd[j] |= (uc << 4) & 0xf0
        addup = addup ^ 1
    return bcd


def hexTobcd(hex):
    bcd = []
    for byte in hex:
        u1 = byte % 10
        u2 = byte / 10
        if u2 > 9:
            u2 = 9
        u1 |= (u2 << 4) & 0xf0

        bcd.append(u1)
    return bcd


def numberToBcd(number, size=0, reverse=True):
    s = str(number)
    bcd = strToBcd(s)

    if size > 0:
        if len(bcd) < size:
            diff = size - len(bcd)
            for i in range(diff):
                bcd.insert(0,0)

    if reverse:
        bcd.reverse()

    return bcd

def bcdTohex(bcd):
    value = []
    for b in bcd:
        uc1 = b & 0x0f
        uc2 = ((b & 0xf0) >> 4) * 10
        uc1 += uc2

        value.append(uc1)
    return value


def bcdToNumber(bcd):
    raw=list(bcd)
    raw.reverse()

    str = bcdToStr(raw)
    value = int(str)
    return value


def bcdToStr(bcd):
    str = []
    for b in bcd:
        str.append("%02x" % b)
        # str.append(hex(b).replace("0x", ""))
    return "".join(str)


def decodeDateTime(raw):
    if len(raw) < 6:
        return None

    bcd = bcdTohex(raw[0:4])

    sec = bcd[0]
    min = bcd[1]
    hour = bcd[2]
    day = bcd[3]

    byte = raw[4]
    month = byte & 0xf
    month = (byte >> 4 & 1) * 10 + month

    bcd = bcdTohex(raw[5:])
    year = 2000 + bcd[0]

    t = datetime.datetime(year, month, day, hour, min, sec)
    return t


def encodeDataTime(t):
    value = []

    value.append(t.second)
    value.append(t.minute)
    value.append(t.hour)
    value.append(t.day)

    value.append(t.month)
    value.append(t.year - 2000)

    return hexTobcd(value)